#!/usr/bin/env python2
#-*- coding: utf-8 -*-

import os
import time
import sys
import inspect 

from optparse import OptionParser 

from Ump import utils
from Ump import defs
from Ump.common.config_base import ConfigManager

def write_config(path, ump_home):
    config_file = '%s/Ump/etc/%s/ump.conf' % (path.rstrip('/'), defs.PRODUCT_NAME)
    configm = ConfigManager(config_file)
    section = 'ump_main'
    configm.set_option(section, home=ump_home)

def exit_returncode(returncode, stdout, stderr):
    if not returncode == 0:
        print >>sys.stderr, stderr
        sys.exit(1)

def install_ump(currpath, installPath):
    if currpath != installPath:
        cp_cmd = 'cp -r %s %s' % (currpath, installPath)
        returncode, stdout, stderr = utils._exec_pipe(cp_cmd)
        exit_returncode(returncode, stdout, stderr)

    os.chdir(installPath) 
    install_cmd = 'python setup.py develop'
    returncode, stdout, stderr = utils._exec_pipe(install_cmd)
    print returncode, stdout, stderr 
    exit_returncode(returncode, stdout, stderr)

def install_option(lichPath='/opt/fusionstack'):
    installPath = os.path.join(lichPath, defs.PRODUCT_NAME)
    path = inspect.getabsfile(install_ump)
    currpath = '/'.join(path.split('/')[0:-1])
    write_config(currpath, lichPath)

    logPath = '%s/../log/ump' % installPath
    if not os.path.exists(logPath):
        os.system('mkdir -p %s' % logPath)

    umpPath = '%s/ump' % installPath
    install_ump(currpath, umpPath)


def main(): 
    usage = 'usage: %prog -C PATH'
    parser = OptionParser(usage=usage)
    parser.add_option("-C", "--path",
            help="ump install path directory DIR"),
    (options, args) = parser.parse_args()
    path = options.path
    print path

    if path is None:
        install_option()
    else:
        install_option(path)


if __name__ == "__main__":
    main()
